package com.juyu.miliao.scheduler.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.builder.BillDetailBeansMqMessageBuilder;
import com.juyu.miliao.common.builder.BillDetailIntegralMqMessageBuilder;
import com.juyu.miliao.common.constant.*;
import com.juyu.miliao.common.constant.enumRedisKey.EnumRedisKey;
import com.juyu.miliao.common.domain.dto.BillDetailBeansDTO;
import com.juyu.miliao.common.domain.dto.BillDetailIntegralDTO;
import com.juyu.miliao.common.domain.dto.UserCallTimesDTO;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.redis.UserCallTimeRedis;
import com.juyu.miliao.common.util.DateUtil;
import com.juyu.miliao.common.util.PageInfoUtil;
import com.juyu.miliao.scheduler.dao.mysql.*;
import com.juyu.miliao.scheduler.dao.redis.VipRedisDao;
import com.juyu.miliao.scheduler.domin.*;
import com.juyu.miliao.scheduler.message.BillDetailIntegralMq;
import com.juyu.miliao.scheduler.message.UserWalletBeansMq;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class QuartzService {
    @Resource
    UserCountDao userCountDao;
    @Resource
    BillDetailDao billDetailDao;
    @Resource
    UserVipDao userVipDao;
    @Resource
    UserInfoDao userInfoDao;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RedisTemplateService redisTemplateService;

    @Resource
    private VipRedisDao vipRedisDao;

    @Resource
    private UserWalletBeansMq userWalletBeansMq;

    @Resource
    private BillDetailIntegralMq billDetailIntegralMq;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private AppkeyDao appKeyDao;

    private static final int pageSize = 5000;

    private static final String DAY_RANKING_DIAMOND_LIST_KEY ="DIAMOND_DAY_RANKING_LIST:";

    private final Logger logger = LoggerFactory.getLogger(QuartzService.class);


    /**
     * 每天晚上8点准时推送给主播
     */
    @Scheduled(cron="0 00 20 * * ?")
    public void sendSystemMessageByHostSort(){
        String type = SpendSystemMessageType.SEND_SYSTEM_MESSAGE_BY_HOST_SORT.getCode();
        String key = DAY_RANKING_DIAMOND_LIST_KEY+LocalDate.now().toString();
        Set<String> userIdSet = stringRedisTemplate.opsForZSet().reverseRange(key,0,-1);
        if(userIdSet ==null || userIdSet.size()==0){
            return;
        }
        int i =0;
        //只取前5个
        String message = "今日钻石榜榜单，加油宝贝\n第一名：%s\n第二名：%s\n第三名：%s\n第四名：%s\n第五名：%s\n";
        String[] args = new String[5];
        String[] colorsArgs = new String[5];
        for(String userId : userIdSet){
            if(i >= 5){
                break;
            }
            User user = userInfoDao.getUserInfoByUserId(Long.parseLong(userId));
            args[i] = user.getNickName();
            colorsArgs[i] = "#fd67c9";
            i++;
        }
        String formatStr=  String.format(message,args);
        List<User> userList = userInfoDao.getUserHost();
        Map<String,Object> ext = new HashMap<>(1);
        Appkey appkey = appKeyDao.getAppkeyByKey("rankingList");
        ext.put("template",message);
        ext.put("templateValue",args);
        ext.put("templateColors",colorsArgs);
        ext.put("redirectUrl",appkey.getValue());
        userList.forEach(user->{
            getSendMsg(user.getUserId(),formatStr,type,ext);
        });
    }

    /**
     * 发送系统消息带扩展
     * @param userId 用户
     * @param message 消息
     * @param type 消息类型
     * @param ext 扩展内容
     */
    public void getSendMsg(long userId ,String message,String type,Map<String,Object> ext) {
        try {
            logger.info("发送通知：userId={},robotId={},message={},type={},ext={}", userId,message,type,ext);
            Map<String, Object> map = new HashMap<>();
            map.put("title", "寻寻");
            map.put("type", type);
            map.put("message", message);
            map.put("ext",ext);
            String createLogInfo= NetEaseCloudUserService.getSystemMessage(objectMapper.writeValueAsString(map), userId);
            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                if(logger.isErrorEnabled()){
                    logger.error("发送自定义系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }
            }
        } catch (Exception e) {
            logger.error("自定义系统消息发送IM错误：参数-" + userId,e);
        }
    }

    @Resource
    private SignInService signInService;
    @Resource
    private BeanWelfareService beanWelfareService;

    // 计算M、V等级定时任务开始
    @Scheduled(cron = "0 05 00 * * ?")
    public void timerToNow() {
        if (logger.isInfoEnabled()) {
            logger.info("计算M、V等级定时任务开始：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
        // 取当前日期
        LocalDate now = LocalDate.now();
        DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
        // 取三个月前日期
        String threeWeeks = now.minusMonths(3).format(dtf);
        String Tomorrow = now.minusMonths(3).plusDays(1).format(dtf);
        if (logger.isInfoEnabled()) {
            logger.info("三个月前日期为:" + threeWeeks);
        }
        int data = userCountDao.countUserCountNum();
        int pageSum = data / 100;
        if (data % 100 > 0) {
            pageSum += 1;
        }
        for (int page = 1; page <= pageSum; page++) {
            int startNum = PageInfoUtil.getOffset(page, pageSize);
            // 取userCount数据
            List<UserCount> userCountList = userCountDao.findUserCountMVGradeSum(startNum, pageSize);
            userCountList.forEach(userCount -> {
                // 计算三个月前日期当天的m值
                // 如果mGradeSum为空 就跳过，因为已经是0就没得再减了
                if (userCount.getMGradeSum() > 0) {
                    BillDetail billDiamond = billDetailDao.findDiamondSumByDay(userCount.getUserId(), threeWeeks, Tomorrow);
                    if (billDiamond != null) {
                        userCountDao.reduceMGradeSum(userCount.getUserId(), billDiamond.getDiamond());
                    }
                }
                // 计算三个月前日期当天的v值
                if (userCount.getVGradeSum() > 0) {
                    BillDetail billSpend = billDetailDao.findSpendSumByDay(userCount.getUserId(), threeWeeks, Tomorrow);
                    if (billSpend != null) {
                        userCountDao.reduceVGradeSum(userCount.getUserId(), billSpend.getSpend());
                    }
                }
            });
        }
        if (logger.isInfoEnabled()) {
            logger.info("结束定时任务：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }

        // 清理排行榜
//		userSortQuartz();
        // 马甲包vip定时任务
//		vestVipPayQuartz();
    }

    /**
     * vip定时任务，添加用户寻币逻辑
     * 每天00：10启动
     */
    @Scheduled(cron = "0 10 00 * * ?")
    public void vipQuartz() {
        logger.info("开始vip定时任务，时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        try {
            List<UserVip> userVipList = userVipDao.getUserVipListByStatus();
            if (userVipList.size() > 0) {
                for (UserVip userVip : userVipList) {
                    LocalDateTime localDateTime = LocalDateTime.now();
                    //判断用户VIP是否过期
                    if (localDateTime.isBefore(userVip.getExpireTime())) {
                        Vip vip = vipRedisDao.getVipInfoById(userVip.getVipId());
                        if (vip != null && vip.getEverydayGiveBeans() > 0) {
                            long beans = vip.getEverydayGiveBeans();

                            BeansType beansType = BeansType.EVERYDAY_VIP_ADD_BEANS;

                            if (VipType.SUPER_VIP_TYPE.getCode() == userVip.getVipType()) {
                                beansType = BeansType.EVERYDAY_SUPPER_VIP_BEANS;
                            }else if(VipType.PLATINUM_VIP_TYPE.getCode() == userVip.getVipType()){
                                beansType = BeansType.EVERYDAY_PLATINUM_VIP_ADD_BEANS;
                            }


                            BillDetailBeansMqMessageBuilder builder = new BillDetailBeansMqMessageBuilder();
                            BillDetailBeansDTO billDetailBeansDTO = builder.userId(userVip.getUserId()).beans(beans)
                                    .beansType(beansType)
                                    .createDate(LocalDate.now(ZoneOffset.of("+8")))
                                    .createTime(LocalDateTime.now(ZoneOffset.of("+8"))).build();

                            userWalletBeansMq.sendUserWalletBeansSumMq(billDetailBeansDTO);
                        }
                    }
                }
                logger.info("结束定时任务，时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
            }
        } catch (Exception ex) {
            logger.info("vip定时任务保存" + ex.getMessage());
        }


    }

    /**
     * 根据通话时长设置用户积分
     * 每天00：10启动
     */
//    @Scheduled(cron = "0 30 9 * * ?")
    @Scheduled(cron = "0 15 00 * * ?")
    public void userCallTimesQuartz() {
        logger.info("根据通话时长设置用户积分，开始时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        try {
            UserCallTimeRedis userCallTimeRedis = new UserCallTimeRedis(stringRedisTemplate);
            List<UserCallTimesDTO> list = userCallTimeRedis.getUserCallTimes(LocalDate.now().minusDays(1));
            for (UserCallTimesDTO obj : list) {
                updateIntegralByUserCallTimes(obj);
            }

            List<User> userList = userInfoDao.getUserHost();
            for (User user : userList) {
                updateIntegralByUserLastCallTime(userCallTimeRedis, user);
            }
            logger.info("根据通话时长设置用户积分，结束时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        } catch (Exception ex) {
            logger.error("根据通话时长设置用户积分异常：[{}]", ex.getMessage());
        }

    }

    /**
     * 根据钻石周榜日榜更新用户积分
     */
    @Scheduled(cron = "0 15 00 * * ?")
    public void diamondRanksByYesterdayAndWeekQuartz() {
        logger.info("根据钻石周榜日榜更新用户积分，开始时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        try {
            //日榜
            String yesterdayKey = DiamondRankingListKey.getDayRankingListKey(LocalDate.now().minusDays(1));
            updateIntegralByRanks(yesterdayKey, RankClass.DIAMOND_RANK.getCode(), RankType.DAY_RANK_TYPE.getCode());
            //周榜
            String weekKey = DiamondRankingListKey.getWeekRankingListKey(LocalDate.now().minusDays(1));
            updateIntegralByRanks(weekKey, RankClass.DIAMOND_RANK.getCode(), RankType.WEEK_RANK_TYPE.getCode());
            logger.info("根据钻石周榜日榜更新用户积分，结束时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        } catch (Exception ex) {
            logger.error("根据钻石周榜日榜设置用户积分异常：[{}]", ex.getMessage());
        }

    }

    /**
     * 根据通话时长周榜日榜更新用户积分
     */
    @Scheduled(cron = "0 15 00 * * ?")
    public void callTimeRanksByYesterdayAndWeekQuartz() {
        logger.info("根据通话时长周榜日榜更新用户积分，开始时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        try {
            //日榜
            String yesterdayKey = CallTimeRankingListKey.getDayRankingListKey(LocalDate.now().minusDays(1));
            updateIntegralByRanks(yesterdayKey, RankClass.CALL_TIME_RANK.getCode(), RankType.DAY_RANK_TYPE.getCode());
            //周榜
            String weekKey = CallTimeRankingListKey.getWeekRankingListKey(LocalDate.now().minusDays(1));
            updateIntegralByRanks(weekKey, RankClass.CALL_TIME_RANK.getCode(), RankType.WEEK_RANK_TYPE.getCode());
            logger.info("根据通话时长周榜日榜更新用户积分，结束时间={}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        } catch (Exception ex) {
            logger.error("根据通话时长周榜日榜设置用户积分异常：[{}]", ex.getMessage());
        }

    }

    /**
     * 根据排行榜更新积分
     *
     * @param key
     * @param rankClass 1:通话榜单，2：钻石榜单
     * @param rankType  1:日榜，2：周榜
     */
    private void updateIntegralByRanks(String key, int rankClass, int rankType) {

        Set<String> set = stringRedisTemplate.opsForZSet().reverseRange(key, 0, 2);
        if (set != null) {
            List<String> list = new ArrayList<>(set);
            for (int i = 1; i <= list.size(); i++) {
                String target = list.get(i - 1);
                try {
                    if (i == 1) {
                        if (rankClass == RankClass.CALL_TIME_RANK.getCode()) {
                            if (rankType == RankType.DAY_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_YESTERDAY_RANKS_FIRST;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            } else if (rankType == RankType.WEEK_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_WEEK_RANKS_FIRST;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        } else if (rankClass == RankClass.DIAMOND_RANK.getCode()) {
                            if(rankType == RankType.DAY_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_YESTERDAY_RANKS_FIRST;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }else if(rankType == RankType.WEEK_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_WEEK_RANKS_FIRST;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        }

                    } else if (i == 2) {
                        if (rankClass == RankClass.CALL_TIME_RANK.getCode()) {
                            if (rankType == RankType.DAY_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_YESTERDAY_RANKS_SECOND;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            } else if (rankType == RankType.WEEK_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_WEEK_RANKS_SECOND;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        } else if (rankClass == RankClass.DIAMOND_RANK.getCode()) {
                            if(rankType == RankType.DAY_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_YESTERDAY_RANKS_SECOND;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }else if(rankType == RankType.WEEK_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_WEEK_RANKS_SECOND;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        }

                    } else if (i == 3) {
                        if (rankClass == RankClass.CALL_TIME_RANK.getCode()) {
                            if (rankType == RankType.DAY_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_YESTERDAY_RANKS_THIRD;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);

                            } else if (rankType == RankType.WEEK_RANK_TYPE.getCode()) {
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .CALL_WEEK_RANKS_THIRD;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        } else if (rankClass == RankClass.DIAMOND_RANK.getCode()) {
                            if(rankType == RankType.DAY_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_YESTERDAY_RANKS_THIRD;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }else if(rankType == RankType.WEEK_RANK_TYPE.getCode()){
                                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                                        .DIAMOND_WEEK_RANKS_THIRD;
                                updateUserIntegralAndCreateBill(Long.parseLong(target), type);
                            }
                        }

                    }
                } catch (Exception ex) {
                    logger.error("根据主播排行榜设置用户积分异常：userId:[{}],异常：[{}]", target, ex);
                }
            }
        }

    }

    /**
     * 根据主播最后通话时间更加积分
     *
     * @param userCallTimeRedis
     * @param user
     */
    private void updateIntegralByUserLastCallTime(UserCallTimeRedis userCallTimeRedis, User user) {
        try {
            String time = userCallTimeRedis.getUserLastCallTimeByUserId(user.getUserId());
            if (StringUtils.isNotBlank(time)) {
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime lastDateTime = LocalDateTime.parse(time, df);
                long day = DateUtil.getBetweenTime(lastDateTime, TimeUnit.DAYS);
                if (day >= 1 && day <= 2) {
                    IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                            .ONE_DAY_NOT_CALL;
                    updateUserIntegralAndCreateBill(user.getUserId(), type);
                } else if (day >= 3 && day <= 4) {
                    IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                            .THREE_DAY_NOT_CALL;
                    updateUserIntegralAndCreateBill(user.getUserId(), type);
                } else if (day >= 5) {
                    IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                            .FIVE_DAY_NOT_CALL;
                    updateUserIntegralAndCreateBill(user.getUserId(), type);
                }
            } else {
                //将不存在的主播设置一个初始时间
                userCallTimeRedis.setUserLastCallTime(user.getUserId());
                logger.info("用户=[{}]初始化最后通话时间", user.getUserId());
            }
        } catch (Exception ex) {
            logger.error("根据主播最后通话时长设置用户积分异常：userId:[{}],异常：[{}]", user.getUserId(), ex);
        }
    }

    /**
     * 更加通话时长更新积分
     *
     * @param obj
     */
    private void updateIntegralByUserCallTimes(UserCallTimesDTO obj) {
        try {
            long userId = obj.getUserId();
            int minutes = obj.getMinutes();

            if (minutes >= 10 && minutes <= 29) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_IS_10_TO_29_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);
            } else if (minutes >= 30 && minutes <= 59) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_IS_30_TO_59_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);
            } else if (minutes >= 60 && minutes <= 99) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_IS_60_TO_99_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);
            } else if (minutes >= 100 && minutes <= 129) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_IS_10_TO_29_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);

            } else if (minutes >= 130 && minutes <= 179) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_IS_130_TO_179_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);

            } else if (minutes >= 180) {
                IntegralRewardsAndPunishmentsType type = IntegralRewardsAndPunishmentsType
                        .DAY_CALL_THAN_180_MINUTES;
                updateUserIntegralAndCreateBill(userId, type);
            }
        } catch (Exception ex) {
            logger.error("根据通话时长设置用户积分异常：userInfo:[{}],异常：[{}]", obj, ex);
        }
    }


    /**
     * 清理排行榜
     * 每天00：01启动
     */
    @Scheduled(cron = "0 01 00 * * ?")
    public void userSortQuartz() {
        if (logger.isInfoEnabled()) {
            logger.info("排行榜定时任务开始：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }

        // 清理每日排行榜数据
        String redisKey = "m:day:" + LocalDate.now().minusDays(2).format(DateTimeFormatter.ISO_DATE);
        Long temp = redisTemplateService.removeUserSortDay(redisKey);
        logger.info("redisKey=" + redisKey + "清除数据量：" + temp);
        temp = redisTemplateService.removeUserSortDay("v:day");
        logger.info("v:day清除数据量：" + temp);
        temp = redisTemplateService.removeUserSortDay("t:day");
        logger.info("t:day清除数据量：" + temp);
        // 判断是否是周一 如果是周一清除week数据
        LocalDateTime now = LocalDateTime.now();// 取当前日期
        int week = now.getDayOfWeek().getValue();
        logger.info("今天是周{}", week);
        if (week == 1) {
            logger.info("清理排行榜week周数据：");
            temp = redisTemplateService.removeUserSortDay("m:week");
            logger.info("m:week清除数据量：temp={}", temp);
            temp = redisTemplateService.removeUserSortDay("v:week");
            logger.info("v:week清除数据量：temp={}", temp);
            temp = redisTemplateService.removeUserSortDay("t:week");
            logger.info("t:week清除数据量：temp={}", temp);
        }
        if (logger.isInfoEnabled()) {
            logger.info("结束排行榜定时任务：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
//		senderEveryDay();
    }


    /**
     * 清理用户每日登录记录，用于发送防诈骗信息
     * 每天00：04启动
     */
    @Scheduled(cron = "0 04 00 * * ?")
    public void userLoginEveryDay() {
        if (logger.isInfoEnabled()) {
            logger.info("清理用户每日登录记录定时任务开始：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
        stringRedisTemplate.delete(EnumRedisKey.SET_USER_LOGIN_EVERYDAY.getValue());
        if (logger.isInfoEnabled()) {
            logger.info("清理用户每日登录记录定时任务：");
            logger.info("时间-" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
        //清除每日能量值限制
        stringRedisTemplate.delete("energyLevelType:1");
        stringRedisTemplate.delete("energyLevelType:2");
        stringRedisTemplate.delete("energyLevelType:3");
        stringRedisTemplate.delete("energyLevelType:4");
        //清理主播提现次数限制
        stringRedisTemplate.delete("userCashEveryDayNumber");
    }


    private BillDetailIntegralDTO getBillDetailIntegralDTO(long userId, int integralValue,
                                                           IntegralRewardsAndPunishmentsType type) {
        BillDetailIntegralMqMessageBuilder mqMessageBuilder = new BillDetailIntegralMqMessageBuilder();
        return mqMessageBuilder.userId(userId)
                .integralRewardsPunishmentsType(type)
                .integralValue(integralValue)
                .createDate(LocalDate.now(ZoneOffset.of("+8")))
                .createTime(LocalDateTime.now(ZoneOffset.of("+8")))
                .build();
    }


    /**
     * 更新积分并生成账单
     *
     * @param userId
     * @param type
     */
    private void updateUserIntegralAndCreateBill(long userId, IntegralRewardsAndPunishmentsType type) {
        userCountDao.updateIntegralSum(userId, type.getIntegralValue());
        BillDetailIntegralDTO target = getBillDetailIntegralDTO(userId, type.getIntegralValue(), type);
        billDetailIntegralMq.getBillDetailIntegralMq(target);
        logger.info("用户[{}],增长积分=[{}]", userId, type.getIntegralValue());
    }

    @Scheduled(cron = "0 02 00 * * ?")
    public void threeDaysNewUser(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        calendar.add(Calendar.DAY_OF_YEAR,-3);
        Date date = calendar.getTime();
        long timestamp = date.getTime();
        Long tempSum = stringRedisTemplate.opsForZSet().zCard("threeDaysNewUser");
        logger.info("清除三天前注册用户---总用户数："+tempSum);
        Long tempRemove = stringRedisTemplate.opsForZSet().removeRangeByScore("threeDaysNewUser",0,timestamp);
        logger.info("清除三天前注册用户---清理用户数："+tempRemove);
        Long tempOver = stringRedisTemplate.opsForZSet().zCard("threeDaysNewUser");
        logger.info("清除三天前注册用户---剩余用户数："+tempOver);
    }

    /**
     * 清理不是30天至内注册的新主播
     * 每天00：05启动
     */
    @Scheduled(cron = "0 05 00 * * ?")
    public void thirtyDaysNewHost(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        calendar.add(Calendar.DAY_OF_YEAR,-30);
        Date date = calendar.getTime();
        long timestamp = date.getTime();
        Long tempSum = stringRedisTemplate.opsForZSet().zCard("thirtyDaysNewHost");
        logger.info("清除三十天前注册主播---总主播数："+tempSum);
        Long tempRemove = stringRedisTemplate.opsForZSet().removeRangeByScore("thirtyDaysNewHost",0,timestamp);
        logger.info("清除三十天前注册主播---清理主播数："+tempRemove);
        Long tempOver = stringRedisTemplate.opsForZSet().zCard("thirtyDaysNewHost");
        logger.info("清除三十天前注册主播---剩余主播数："+tempOver);
    }

    /**
     * 重置签到天数
     */
    @Scheduled(cron = "0 01 00 * * ?")
    public void resetSignInData() {
        signInService.resetSignInData();
    }

    /**
     * 重置寻豆福利领取状态
     */
    @Scheduled(cron = "0 01 00 * * ?")
    public void resetBeanWelfareStatues() {
        beanWelfareService.resetBeanWelfareStatues();
    }

    /**
     * 1.5.6删除昨日 主播每小时收益
     */
    @Scheduled(cron = "0 01 00 * * ?")
    public void resetHomeListIncomeByHostUser(){
        LocalDate localDate = LocalDate.now().minusDays(1);
        for(int i = 0; i<=24 ;i++){
            stringRedisTemplate.delete("homeListIncomeByHostUser:"+localDate.toString()+":"+i);
        }
    }

}
